package com.zf.shuashua;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.alibaba.sdk.android.vod.upload.VODUploadCallback;
import com.alibaba.sdk.android.vod.upload.VODUploadClient;
import com.alibaba.sdk.android.vod.upload.VODUploadClientImpl;
import com.alibaba.sdk.android.vod.upload.model.UploadFileInfo;
import com.alibaba.sdk.android.vod.upload.model.VodInfo;
import com.aliyun.apsara.alivclittlevideo.net.LittleHttpManager;
import com.aliyun.apsara.alivclittlevideo.sts.StsInfoManager;
import com.aliyun.apsara.alivclittlevideo.view.mine.AlivcLittleUserManager;
import com.aliyun.common.utils.DensityUtil;
import com.aliyun.svideo.base.utils.UploadConstant;
import com.aliyun.svideo.common.utils.ToastUtils;
import com.bumptech.glide.Glide;
import com.duoyou.task.openapi.DyAdApi;
import com.lxj.xpopup.XPopup;
import com.meis.base.mei.entity.Result;
import com.meis.base.mei.utils.ParseJsonUtils;
import com.mob.secverify.PreVerifyCallback;
import com.mob.secverify.SecVerify;
import com.mob.secverify.exception.VerifyException;
import com.tencent.bugly.beta.Beta;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.inapp.InAppMessageManager;
import com.umeng.socialize.UMShareAPI;
import com.vise.xsnow.http.callback.ACallback;
import com.zf.shuashua.advert.AdManager;
import com.zf.shuashua.advert.AdvertConfigManager;
import com.zf.shuashua.advert.CommitUtils;
import com.zf.shuashua.advert.MistakeConfigManager;
import com.zf.shuashua.advert.RewardAdvertFragment;
import com.zf.shuashua.advert.RewardAdvertHwManager;
import com.zf.shuashua.advert.mg.AdDataBean;
import com.zf.shuashua.advert.mg.MGReportManager;
import com.zf.shuashua.advert.mg.MLog;
import com.zf.shuashua.advert.mg.ReportLocationType;
import com.zf.shuashua.api.AbsCallback;
import com.zf.shuashua.api.Constants;
import com.zf.shuashua.api.HttpData;
import com.zf.shuashua.api.Store;
import com.zf.shuashua.base.BaseActivity;
import com.zf.shuashua.bean.BannerBean;
import com.zf.shuashua.bean.BaseData;
import com.zf.shuashua.bean.ButtleDoubleStatus;
import com.zf.shuashua.bean.ConfigInfo;
import com.zf.shuashua.bean.ExtraBean;
import com.zf.shuashua.bean.InviteStatus;
import com.zf.shuashua.bean.JumpJson;
import com.zf.shuashua.bean.LoginBean;
import com.zf.shuashua.bean.Me;
import com.zf.shuashua.bean.Reward;
import com.zf.shuashua.bean.UpImage;
import com.zf.shuashua.bean.UploadAuthBean;
import com.zf.shuashua.common.PhoneCallManager;
import com.zf.shuashua.manager.LocationListener;
import com.zf.shuashua.manager.LocationManager;
import com.zf.shuashua.manager.LoginRecordManager;
import com.zf.shuashua.manager.track.TrackConstants;
import com.zf.shuashua.manager.track.TrackManager;
import com.zf.shuashua.receiver.NetWorkStateReceiver;
import com.zf.shuashua.ui.game.GameFragment;
import com.zf.shuashua.ui.gift.GiftFragment;
import com.zf.shuashua.ui.gift.H5Activity;
import com.zf.shuashua.ui.home.HomeCommentFragment;
import com.zf.shuashua.ui.home.HomeFragment;
import com.zf.shuashua.ui.home.HotHomeFragment;
import com.zf.shuashua.ui.home.PrivacyPopup;
import com.zf.shuashua.ui.mine.LogUtil;
import com.zf.shuashua.ui.mine.LoginActivity;
import com.zf.shuashua.ui.mine.MineFragment;
import com.zf.shuashua.ui.popup.CommonNoAdPopup;
import com.zf.shuashua.ui.popup.ExitPopup;
import com.zf.shuashua.ui.popup.FriendInvitationPopup;
import com.zf.shuashua.ui.popup.GuafenPopup;
import com.zf.shuashua.ui.popup.LocationDialog;
import com.zf.shuashua.ui.popup.NewUserDialog;
import com.zf.shuashua.ui.popup.NoticeTipDialog;
import com.zf.shuashua.ui.popup.OnPopupListener;
import com.zf.shuashua.utils.ClipBoardUtil;
import com.zf.shuashua.utils.CommonConstants;
import com.zf.shuashua.utils.ManufacturerInfoUtils;
import com.zf.shuashua.utils.TextUtil;
import com.zf.shuashua.utils.TimeUtils;
import com.zf.shuashua.utils.ToNotification;
import com.zf.shuashua.utils.ToastUtil;
import com.zf.shuashua.widget.CircleProgressView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.tongdun.android.shell.FMAgent;
import me.yokeyword.fragmentation.ISupportFragment;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    public static final int HOME_INDEX = 0;
    private static final int HOT_INDEX = 1;
    private static final int GIFT_INDEX = 2;
    private static final int GAME_INDEX = 3;
    private static final int MINE_INDEX = 4;
    public static final int WITHDRAW = 8;//提现
    public static boolean isPreVerifyDone = false;//一键登入预初始化是否完成
    private LinearLayout tabHome, tabHot, tabMine;
    private ConstraintLayout tabGame;
    private ImageView tabGift;
    private ImageView imgHome, imgMine, imgReceive;
    private TextView txtHome, txtHot, txtGame, txtMine;
    public boolean gift;
    GameFragment gameFragment;
    HomeFragment homeFragment;
    HotHomeFragment hotHomeFragment;
    GiftFragment giftFragment;
    MineFragment mineFragment;
    FrameLayout mFlUploadVideo;
    ImageView mIvThumb;
    CircleProgressView mCircleProgress;
    private HomeCommentFragment mHomeCommentFragment;
    private NetWorkStateReceiver netWorkStateReceiver;
    private ExitPopup popupView;
    private int lastIndex = 0;
    private boolean isnewuser;

    @Override
    protected void initView() {
        tabHome = findViewById(R.id.tab_home);
        tabHot = findViewById(R.id.tab_hot);
        tabGame = findViewById(R.id.tab_game);
        tabGift = findViewById(R.id.tab_make_money);
        tabMine = findViewById(R.id.tab_mine);
        txtHome = findViewById(R.id.txt_home);
        txtHot = findViewById(R.id.txt_hot);
        txtGame = findViewById(R.id.txt_game);
        txtMine = findViewById(R.id.txt_mine);
        tabHome.setOnClickListener(this);
        tabHot.setOnClickListener(this);
        tabGame.setOnClickListener(this);
        tabGift.setOnClickListener(this);
        tabMine.setOnClickListener(this);
        imgHome = findViewById(R.id.img_home);
        imgMine = findViewById(R.id.img_mine);
        imgReceive = findViewById(R.id.imgReceive);

        mFlUploadVideo = findViewById(R.id.fl_upload);
        mIvThumb = findViewById(R.id.iv_thumb);
        mCircleProgress = findViewById(R.id.progress_view);
        initFragments();
        tabHome.performClick();

        syncAdvertSource();
        getConfigInfo();
        TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_TASK, TrackConstants.ACTION_LOGIN_START, TrackConstants.NOTE_LOGIN_START);
        PhoneCallManager.getInstance().startService(this);
        LittleHttpManager.getInstance().init(this);
        AlivcLittleUserManager.getInstance().init(this);
        StsInfoManager.getInstance().getStsToken();
        requestPermission();
        setupFMAgent();

        imgReceive.setBackgroundResource(R.drawable.linqu_animation);
        AnimationDrawable animal = (AnimationDrawable) imgReceive.getBackground();
        animal.start();
    }

    private void requestPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
                    //  用户彻底拒绝授予权限，一般会提示用户进入设置权限界面
                } else {
                    //  用户未彻底拒绝授予权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 2);
                }
            }
        }
    }

    /**
     * 同盾SDK初始化
     * PS:同盾sdk在显式调用的情况下，每十分钟只会采集一次设备数据
     */
    private void setupFMAgent() {
        String box = FMAgent.ENV_PRODUCTION;
        FMAgent.initWithCallback(this, box, s -> {
            runOnUiThread(() -> {
                ShuaApplication.blackbox = s;
            });
        });
    }

    @Override
    protected void initData() {
        //是否支持一键登入环境#####MOB
        if (SecVerify.isVerifySupport() && !Store.getInstance().isLogin()) {
            preVerify();
        }
        Beta.checkUpgrade(false, false);
        LoginRecordManager.getInstance().loginRecord();
        TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_LOGIN, TrackConstants.ACTION_LOGIN_START, TrackConstants.NOTE_LOGIN_START);
        if (netWorkStateReceiver == null) {
            netWorkStateReceiver = new NetWorkStateReceiver();
        }
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(netWorkStateReceiver, filter);
        activityPop();
        initReceiver();
        observableMe();
        startLocation();
        if (BuildConfig.ENABLE_DEBUG) {
            InAppMessageManager.getInstance(this).setInAppMsgDebugMode(true);//设置测试模式
        }
        //插屏消息关闭时，会回调该方法
        InAppMessageManager.getInstance(this).showCardMessage(this, "main", () -> {
        });
        checkLocation();
        preLoadHwAdvert();
    }

    /**
     * 预加载华为激励视频
     */
    private void preLoadHwAdvert() {
        if (ManufacturerInfoUtils.isHuawei() && Store.getInstance().isLogin()) {
            RewardAdvertHwManager.getInstance().loadAd(this);
        }
    }

    /**
     * 预登录
     * <p>
     * 建议提前调用预登录接口，可以加快免密登录过程，提高用户体验
     */
    private void preVerify() {
        isPreVerifyDone = false;
        //设置在1000-10000之内
        SecVerify.setTimeOut(5000);
        //移动的debug tag 是CMCC-SDK,电信是CT_ 联通是PriorityAsyncTask
        SecVerify.setDebugMode(true);
        SecVerify.setUseCache(true);
        SecVerify.preVerify(new PreVerifyCallback() {
            @Override
            public void onComplete(Void data) {
                isPreVerifyDone = true;
            }

            @Override
            public void onFailure(VerifyException e) {
                isPreVerifyDone = true;
                Throwable t = e.getCause();
                String errDetail = null;
                if (t != null) {
                    errDetail = t.getMessage();
                }
                // 错误码
                int errCode = e.getCode();
                // 错误信息
                String errMsg = e.getMessage();
                // 更详细的网络错误信息可以通过t查看，请注意：t有可能为null
                String msg = "错误码: " + errCode + "\n错误信息: " + errMsg;
                if (!TextUtils.isEmpty(errDetail)) {
                    msg += "\n详细信息: " + errDetail;
                }
                LogUtil.d(msg + "-----==");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        UMShareAPI.get(this).release();
        try {
            PhoneCallManager.getInstance().stopService(this);
            AdManager.getInstance().onDestroy(this);
            unregisterReceiver(netWorkStateReceiver);
            unregisterReceiver(receiver);
        } catch (Exception ignored) {

        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    /**
     * 同步本地的开关信息到application
     */
    private void syncAdvertSource() {

    }

    private boolean hasJumpLocation = false;

    private void checkLocation() {
        if (Store.getInstance().isRemindLocation()) {
            return;
        }
        try {
            boolean isLocationEnabled = isLocationEnabled();
            if (!isLocationEnabled) {
                Store.getInstance().setRemindLocation(true);
                LocationDialog locationDialog = new LocationDialog(this);
                locationDialog.setPopupListener(new OnPopupListener() {
                    @Override
                    public void onNext() {
                        hasJumpLocation = true;
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }

                    @Override
                    public void onClose() {

                    }
                });
                locationDialog.show();
            }
        } catch (Exception ignored) {

        }
    }

    private void startLocation() {
        LocationManager.getInstance().startLocation(this, new LocationListener() {
            @Override
            public void onSuccess(String city) {
//                ToastUtil.show(mContext, city);
                MistakeConfigManager.getInstance().fetchConfig(city);
            }

            @Override
            public void onFail() {
                String city = Store.getInstance().getLastLocation();
                MistakeConfigManager.getInstance().fetchConfig(city);
            }
        });
    }

    public boolean isLocationEnabled() {
        int locationMode = 0;
        String locationProviders;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            try {
                locationMode = Settings.Secure.getInt(getContentResolver(), Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return locationMode != Settings.Secure.LOCATION_MODE_OFF;
        } else {
            locationProviders = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
            return !TextUtils.isEmpty(locationProviders);
        }
    }

    private void getConfigInfo() {
        getCommonConfig();
        AdvertConfigManager.getInstance().getNewAdvertConfig();
    }

    /**
     * 通用开关
     */
    private void getCommonConfig() {
        HttpData.getInstance().getConfigInfo(new AbsCallback<BaseData<ConfigInfo>>() {
            @Override
            public void onRealSuccess(BaseData<ConfigInfo> data) {
                ConfigInfo configInfo = data.getData();
                if (configInfo == null) return;

                int rate = configInfo.getHome_ad_refresh_rate();
                if (rate <= 0) {
                    rate = 4;
                }
                ShuaApplication.adRefreshRate = rate;
                int horizontalRate = configInfo.getAdvert_video_ad_num();
                if (horizontalRate <= 0) {
                    horizontalRate = 1;
                }
                ShuaApplication.horizontalRate = horizontalRate;
                try {
                    ShuaApplication.multiple_min = Integer.parseInt(configInfo.getMultiple_min());
                    ShuaApplication.multiple_max = Integer.parseInt(configInfo.getMultiple_max());


                } catch (Exception e) {

                }

                Store.getInstance().saveConfigInfo(configInfo);
            }

            @Override
            public void onFail(int errCode, String errMsg) {
            }
        });
    }


    private void initFragments() {
        homeFragment = new HomeFragment();
        hotHomeFragment = HotHomeFragment.newInstance();
        giftFragment = new GiftFragment();
        gameFragment = GameFragment.newInstance();
        mineFragment = new MineFragment();
        loadMultipleRootFragment(R.id.container, 0, homeFragment, hotHomeFragment, giftFragment, gameFragment, mineFragment);
        if (!Store.getInstance().getNewUserPopup()) {
            showNewUser();
        }
    }

    private void showNewUser() {
        NewUserDialog dialog = new NewUserDialog(this, "立即领取");
        dialog.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                Store.getInstance().setNewUserPopup(true);
                startActivity(new Intent(MainActivity.this, LoginActivity.class));

            }

            @Override
            public void onClose() {
                Store.getInstance().setNewUserPopup(true);
            }
        });
        dialog.show();
    }

    //获取剪切板内容
    private void getClipboardData() {
        this.getWindow().getDecorView().postDelayed(() -> {
            String past = ClipBoardUtil.paste();
            checkInvitePopup(past);
        }, 400);
    }

    /**
     * 是否弹出好友助力弹框
     */
    public void checkInvitePopup(String past) {
        if (Store.getInstance().isLogin()) {
            ClipBoardUtil.clear();
        }
        if (TextUtils.isEmpty(past)) {
            return;
        }
        if (past.contains("苌荳葮视蘋")) {
            HttpData.getInstance().getEntryStatus(past, new AbsCallback<BaseData<InviteStatus>>() {
                @Override
                public void onRealSuccess(BaseData<InviteStatus> data) {
                    if (data == null || data.getData() == null) {
                        return;
                    }
                    if (data.getData().isShow()) {
                        showFriendInvitation(data.getData());
                    }
                }
            });
        }
    }

    /**
     * 好友助力
     */
    private void showFriendInvitation(InviteStatus inviteStatus) {
        TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_HOME_INVITE_POP, TrackConstants.NOTE_HOME_INVITE_POP);
        FriendInvitationPopup dialog = new FriendInvitationPopup(this, inviteStatus.getAvatar(), inviteStatus.getName());
        dialog.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_HOME_INVITE_GO, TrackConstants.NOTE_HOME_INVITE_GO);
                startActivity(new Intent(mContext, H5Activity.class).putExtra("money", Constants.H5_URL + "invite_help?shareInviteCode=" + inviteStatus.getInvite_code()).putExtra("title", "邀新送礼"));
            }

            @Override
            public void onClose() {
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_HOME_INVITE_CLOSE, TrackConstants.NOTE_HOME_INVITE_CLOSE);

            }
        });
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == CommonConstants.MAIN) {
            if (resultCode == RESULT_OK) {
                openHome();
            }
        } else if (requestCode == WITHDRAW) {
            if (resultCode == RESULT_OK) {
                try {
                    String taskType = data.getStringExtra("taskType");
                    dealWithdrawResult(taskType);
                } catch (Exception e) {
                    openHome();
                }
            }
        }
    }

    private void dealWithdrawResult(String taskType) {
        if (TextUtils.isEmpty(taskType)) {
            openGift();
            scrollToModle("theTaskMod");
            return;
        }
        if ("task".equals(taskType)) {
            openGift();
            scrollToModle("theTaskMod");
            return;
        }
        if ("friend".equals(taskType)) {
            jumpToFriend();
        } else if ("home".equals(taskType)) {
            openHome();
        } else if ("game".equals(taskType)) {
            DyAdApi.getDyAdApi().jumpAdList(this, Store.getInstance().getuserId(), 0);
            ;
        }
    }

    private void jumpToFriend() {
        if (!ToLogin()) {
            startActivity(new Intent(this, H5Activity.class).putExtra("money", Constants.H5_URL + "helpEarn").putExtra("title", "邀请好友").putExtra("Refresh", true));
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (hasJumpLocation) {
            startLocation();
        }
        Intent intent = getIntent();
        isnewuser = false;
        if (intent != null) {
            Serializable serializable = intent.getSerializableExtra("loginDataBean");
            Serializable serializable1 = intent.getSerializableExtra("bean");
            if (serializable instanceof LoginBean.DataBean) {
                TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_REGISTER_SUCCEED, TrackConstants.NOTE_REGISTER_SUCCEED);
                //新人礼弹窗
                intent.putExtra("loginDataBean", "null");
                LoginBean.DataBean loginDataBean = (LoginBean.DataBean) serializable;
                if (loginDataBean.isIs_new_user()) {
                    isnewuser = true;
//                    Store.getInstance().setIsNewUser(false);
                    NewUserDialog dialog = new NewUserDialog(this, "立即领取");
                    dialog.setPopupListener(new OnPopupListener() {
                        @Override
                        public void onNext() {
                            CommonNoAdPopup giftSignPopup = new CommonNoAdPopup(MainActivity.this, "领取成功!", "去提现", "3.3", "0");
                            giftSignPopup.setPopupListener(new OnPopupListener() {
                                @Override
                                public void onNext() {
                                    startActivityForResult(new Intent(MainActivity.this, H5Activity.class).putExtra("money", Constants.H5_URL + "withdraw?isNewUser=1").putExtra("title", "我的钱包"), WITHDRAW);
                                    giftSignPopup.dismiss();
                                }

                                @Override
                                public void onClose() {

                                }
                            });
                            new XPopup.Builder(MainActivity.this)
                                    .asCustom(giftSignPopup)
                                    .show();
                        }


                        @Override
                        public void onClose() {
                        }
                    });
                    dialog.show();
                }

            } else if (serializable1 instanceof ExtraBean) {
                //通知条状任务页面
                ExtraBean extraBean = (ExtraBean) serializable1;
                intent.putExtra("bean", "null");
                if (extraBean.getOpen_id() == 1) {
                    openHome();
                } else if (extraBean.getOpen_id() == 2) {
                    openGift();
                } else if (extraBean.getOpen_id() == 3) {
                    openMine();
                } else {
                    openHome();
                }
            }
        }
        getClipboardData();
    }


    public void activityPop() {
        tabHome.postDelayed(() -> {
            if (Store.getInstance().isLogin() && !isnewuser) {


                //该方法 找不到，注释
//                HttpData.getInstance().getActivityPopup(new ACallback<BaseData<Reward>>() {
//                    @Override
//                    public void onSuccess(BaseData<Reward> data) {
//                        LogUtil.d("nchenggong");
//                    }
//
//                    @Override
//                    public void onFail(int errCode, String errMsg) {
//                        LogUtil.d(errMsg);
//
//                    }
//                });
                HttpData.getInstance().getUserBannerList("3", new ACallback<String>() {
                    public void onSuccess(String data) {
                        List<BannerBean> bannerList = ParseJsonUtils.parseListData(data, "data", BannerBean.class);
                        Store instance = Store.getInstance();
                        Date now = new Date();
                        if (bannerList != null && bannerList.size() != 0) {//data不空就是开启弹窗的时间
                            if (instance.getBackTasksPupopDay() == -1) {
                                instance.setBackTasksPupopDay(bannerList.get(0).popup_tian);//每几天弹一次
                            }
                            if (instance.getBackTasksPupopSum() == -1) {
                                instance.setBackTasksPupopSum(bannerList.get(0).popup_ci);//每天弹几次
                            }
                            if ("".equals(instance.getBackTasksTime())) {
                                //保存开启弹窗时间
                                instance.setBackTasksTime(TimeUtils.dateToStr(now));
                            } else {
                                if (TimeUtils.differentDaysByMillisecond(TimeUtils.strToDate(instance.getBackTasksTime()), now) >= instance.getBackTasksPupopDay()) {
                                    instance.setBackTasksTime(TimeUtils.dateToStr(now));
                                    instance.setBackTasksPupopSum(bannerList.get(0).popup_ci);//每天弹几次
                                }

                            }

                            if (instance.getBackTasksPupopSum() > 0) {
                                //一天弹几次
                                instance.setBackTasksPupopSum(instance.getBackTasksPupopSum() - 1);
                                new XPopup.Builder(MainActivity.this)
                                        .dismissOnTouchOutside(false)
                                        .dismissOnBackPressed(false)
                                        .asCustom(new GuafenPopup(MainActivity.this, bannerList.get(0).id, bannerList.get(0).jump_link, bannerList.get(0).banner_name, bannerList.get(0).banner_url))
                                        .show();
                            }

                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {

                    }
                });
            }

        }, 3000);
    }

    private void observableMe() {
        if (Store.getInstance().isLogin()) {
            HttpData.getInstance().getMe(new ACallback<Me>() {
                @Override
                public void onSuccess(Me data) {
                    if (data.isStatus() && data.getData() != null) {
                        ShuaApplication.game_status = data.getData().isGame_status();
                        Store.getInstance().setNEW_OR_OLD(data.getData().isNew_or_old());//新老用户
                        //别名增加，将某一类型的别名ID绑定至某设备，老的绑定设备信息还在，别名ID和device_token是一对多的映射关系
                        PushAgent.getInstance(MainActivity.this).setAlias(data.getData().getLogin_user_id() + "", "ALIAS_TYPE_LOGIN", new UTrack.ICallBack() {
                            @Override
                            public void onMessage(boolean isSuccess, String message) {

                            }
                        });
                    }
                }

                @Override
                public void onFail(int errCode, String errMsg) {
                }
            });
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        openHome();

        getStsInfo(intent);
    }


    private void getStsInfo(final Intent intent) {
        if (intent == null) return;
        final String videoPath = intent.getStringExtra(UploadConstant.KEY_UPLOAD_VIDEO);
        if (TextUtils.isEmpty(videoPath)) return;
        String videoName = "";
        try {
            videoName = videoPath.substring(videoPath.lastIndexOf("/") + 1);
        } catch (Exception e) {
            videoName = "changdou.mp4";
        }

        HttpData.getInstance().getUploadAuth("android/" + videoName, videoPath, new ACallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (!TextUtils.isEmpty(data)) {
                    Result<UploadAuthBean> bean = ParseJsonUtils.parseDataToResult(data, UploadAuthBean.class);
                    if (bean.code == 200 && bean.data != null) {
                        uploadVideo(intent, bean.data);
                    }
                }
            }

            @Override
            public void onFail(int errCode, String errMsg) {
            }
        });
    }

    private void uploadVideo(Intent intent, final UploadAuthBean bean) {
        mCircleProgress.setProgress(1);
        String videoPath = intent.getStringExtra(UploadConstant.KEY_UPLOAD_VIDEO);

        mFlUploadVideo.setVisibility(View.VISIBLE);
        String mThumbnailPath = getIntent().getStringExtra(UploadConstant.KEY_UPLOAD_THUMBNAIL);
        float mRatio = getIntent().getFloatExtra(UploadConstant.KEY_PARAM_VIDEO_RATIO, 0f);
        String mDesc = getIntent().getStringExtra(UploadConstant.KEY_UPLOAD_DESC);
        boolean isRecordVideo = getIntent().getBooleanExtra(UploadConstant.KEY_PARAM_IS_RECORD_VIDEO, false);

        if (!TextUtils.isEmpty(mThumbnailPath)) {
            Glide.with(this)
                    .load(mThumbnailPath)
                    .into(mIvThumb);
        }

        File file = new File(mThumbnailPath);
        if (file.exists()) {
            HttpData.getInstance().getUploadImg(file, new ACallback<UpImage>() {
                @Override
                public void onSuccess(UpImage data) {
                    if (data != null && data.getData() != null) {
                        uploadAuthVideo(bean, videoPath, data.getData().getUrl(), mDesc, isRecordVideo);
                    }
                }

                @Override
                public void onFail(int errCode, String errMsg) {
                    runOnUiThread(() -> {
                        mFlUploadVideo.setVisibility(View.GONE);
                        ToastUtils.show(getBaseContext(), "上传成功");
                    });
                }
            });
        }

    }

    private void uploadAuthVideo(final UploadAuthBean bean, String
            videoPath, String coverUrl, String desc, boolean isRecordVideo) {
        VODUploadClient uploader = new VODUploadClientImpl(getApplicationContext());
        VODUploadCallback callback = new VODUploadCallback() {
            @Override
            public void onUploadSucceed(UploadFileInfo info) {
                super.onUploadSucceed(info);

                HttpData.getInstance().postVideoInfo(isRecordVideo ? "1" : "2", bean.VideoId, desc, coverUrl, new ACallback<String>() {
                    @Override
                    public void onSuccess(String data) {
                        mFlUploadVideo.setVisibility(View.GONE);
                        if (ParseJsonUtils.parseFieldData(data, "code").equals("200")) {
                            ToastUtil.show(getBaseContext(), "视频上传成功");
                        }
                    }

                    @Override
                    public void onFail(int errCode, String errMsg) {
                        mFlUploadVideo.setVisibility(View.GONE);
                        ToastUtil.show(getBaseContext(), "视频上传失败");
                    }
                });
            }

            @Override
            public void onUploadFailed(UploadFileInfo info, String code, String message) {
                super.onUploadFailed(info, code, message);
                runOnUiThread(() -> {
                    mFlUploadVideo.setVisibility(View.GONE);
                    ToastUtils.show(getBaseContext(), "上传失败");
                });
            }

            @Override
            public void onUploadProgress(UploadFileInfo info, long uploadedSize, long totalSize) {
                super.onUploadProgress(info, uploadedSize, totalSize);

                final int progress = (int) (uploadedSize * 100 / totalSize);
                runOnUiThread(() -> {
                    mCircleProgress.setProgress(progress);
                });
            }

            @Override
            public void onUploadTokenExpired() {
                super.onUploadTokenExpired();
                runOnUiThread(() -> mFlUploadVideo.setVisibility(View.GONE));
            }

            @Override
            public void onUploadRetry(String code, String message) {
                super.onUploadRetry(code, message);
            }

            @Override
            public void onUploadRetryResume() {
                super.onUploadRetryResume();
            }

            @Override
            public void onUploadStarted(UploadFileInfo uploadFileInfo) {
                super.onUploadStarted(uploadFileInfo);

                uploader.setUploadAuthAndAddress(uploadFileInfo, bean.UploadAuth, bean.UploadAddress);
            }
        };

        uploader.init(callback);

        String filePath = videoPath;
        VodInfo vodInfo = new VodInfo();
        vodInfo.setTitle("android短视频");
        vodInfo.setDesc(desc);
        vodInfo.setCateId(19);
        vodInfo.setCoverUrl(coverUrl);
        uploader.addFile(filePath, vodInfo);

        uploader.start();
    }

    public void openHome() {
        runOnUiThread(() -> {
            tabHome.performClick();
        });
    }

    public void openHot() {
        runOnUiThread(() -> {
            tabHot.performClick();
        });
    }

    public void openGift() {
        runOnUiThread(() -> tabGift.performClick());
    }

    public void openGame() {
        runOnUiThread(() -> tabGame.performClick());
    }

    public void scrollToModle(String modName) {
        new Handler().postDelayed(() -> giftFragment.scrollToModle(modName), 500);
    }

    public void openMine() {
        runOnUiThread(() -> tabMine.performClick());
    }

    private void startTaskAnimator() {
        try {
            tabGift.setBackgroundResource(R.drawable.task_gad_animation_list);
            AnimationDrawable animal = (AnimationDrawable) tabGift.getBackground();
            animal.start();
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    animal.stop();
                    tabGift.setBackgroundResource(R.drawable.tab_gift_selector);
                }
            }, 690);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        gift = false;
        int index = 0;
        if (i == R.id.tab_home) {
            index = HOME_INDEX;
            imgHome.setSelected(true);
            imgMine.setSelected(false);
            tabGift.setSelected(false);
            tabGift.setBackgroundResource(R.drawable.tab_gift_selector);
            txtHome.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            txtHome.setAlpha(1f);
            txtHot.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtHot.setAlpha(0.5F);
            txtGame.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtGame.setAlpha(0.5F);
            txtMine.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtMine.setAlpha(0.5F);
        } else if (i == R.id.tab_make_money) {
            TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_TASK, TrackConstants.ACTION_TASK_INTO, TrackConstants.NOTE_TASK_INTO);
            gift = true;
            index = GIFT_INDEX;
            imgHome.setSelected(false);
            imgMine.setSelected(false);
            tabGift.setSelected(true);
            txtHome.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtHome.setAlpha(0.5F);
            txtHot.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtHot.setAlpha(0.5F);
            txtGame.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtGame.setAlpha(0.5F);
            txtMine.setAlpha(0.5F);
            txtMine.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));

            startTaskAnimator();
        } else if (i == R.id.tab_hot) {
            index = HOT_INDEX;
            TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_HOME_HOT, TrackConstants.NOTE_HOME_HOT);
            imgHome.setSelected(false);
            imgMine.setSelected(true);
            tabGift.setSelected(false);
            tabGift.setBackgroundResource(R.drawable.tab_gift_selector);
            txtHome.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtHome.setAlpha(0.5F);
            txtHot.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            txtHot.setAlpha(1F);
            txtGame.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtGame.setAlpha(0.5F);
            txtMine.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtMine.setAlpha(0.5F);
        } else if (i == R.id.tab_game) {
            if (ShuaApplication.game_status && !CommitUtils.isCloseGame()) {
                if (!ToLogin()) {
                    TrackManager.getInstance().reportAdvertAction(TrackConstants.PAGE_ID_NEW, TrackConstants.ACTION_WEAL_INTO, TrackConstants.NOTE_WEAL_INTO);
                    index = GAME_INDEX;
                    imgHome.setSelected(false);
                    imgMine.setSelected(true);
                    tabGift.setSelected(false);
                    tabGift.setBackgroundResource(R.drawable.tab_gift_selector);
                    txtHome.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    txtHome.setAlpha(0.5F);
                    txtHot.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    txtHot.setAlpha(0.5F);
                    txtGame.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    txtGame.setAlpha(1F);
                    txtMine.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
                    txtMine.setAlpha(0.5F);
                }
            } else {
                if (!ToLogin()) {
                    startActivityForResult(new Intent(this, H5Activity.class).putExtra("money", Constants.H5_URL + "withdraw").putExtra("title", "我的钱包"), WITHDRAW);
                }
            }
        } else if (i == R.id.tab_mine) {
            index = MINE_INDEX;
            imgHome.setSelected(false);
            imgMine.setSelected(true);
            tabGift.setSelected(false);
            tabGift.setBackgroundResource(R.drawable.tab_gift_selector);
            txtHome.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtHome.setAlpha(0.5F);
            txtHot.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtHot.setAlpha(0.5F);
            txtGame.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            txtGame.setAlpha(0.5F);
            txtMine.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            txtMine.setAlpha(1F);
        }
        if (lastIndex != index) {
            showHideFragment(getIndexFragment(index), getIndexFragment(lastIndex));
        }
        lastIndex = index;
    }

    private ISupportFragment getIndexFragment(int index) {
        if (index == HOME_INDEX) {
            return homeFragment;
        } else if (index == HOT_INDEX) {
            return hotHomeFragment;
        } else if (index == GIFT_INDEX) {
            return giftFragment;
        } else if (index == GAME_INDEX) {
            return gameFragment;
        } else if (index == MINE_INDEX) {
            return mineFragment;
        }
        return homeFragment;
    }

    private boolean ToLogin() {
        if (!Store.getInstance().isLogin()) {
            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            return true;
        }
        return false;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        boolean isConsume = giftFragment.isConsume(keyCode, event);
        return isConsume || super.onKeyDown(keyCode, event);
    }

    @Override
    public void onBackPressedSupport() {
        if (isAddedFragment(RewardAdvertFragment.class.getName())) {
            return;
        }
        if (mHomeCommentFragment != null && mHomeCommentFragment.isShowing()) {
            mHomeCommentFragment.hideBehavior();
            return;
        }
        if (giftFragment != null && giftFragment.isShowPopup()) {
            return;
        }
        if (gameFragment != null && gameFragment.isShowPopup()) {
            return;
        }
//        if (XZBackHandlerHelper.handleBackPress(this)) {
//            return;
//        }
        popupView = new ExitPopup(MainActivity.this);
        popupView.setPopupListener(new OnPopupListener() {
            @Override
            public void onNext() {
                openHome();
            }

            @Override
            public void onClose() {
                MobclickAgent.onKillProcess(getApplicationContext());
                System.exit(0);
            }
        });
        new XPopup.Builder(MainActivity.this)
                .dismissOnTouchOutside(false)
                .dismissOnBackPressed(false)
                .asCustom(popupView)
                .show();
    }

    /**
     * 显示评论页
     */
    public void showReviewFragment() {
        if (mHomeCommentFragment == null) return;
        mHomeCommentFragment.showBehavior();
    }

    /**
     * 隐藏评论页
     */
    public void hideReviewFragment() {
        if (mHomeCommentFragment == null) return;
        hideFragment(mHomeCommentFragment);
    }

    // 关闭评论弹窗
    public void closeCommentDialog() {
        if (mHomeCommentFragment == null) return;
        mHomeCommentFragment.hideBehavior();
    }

    public void showBottomComment(String videoId, String headUrl, int commentCount,
                                  int position) {
        showFragment(R.id.fl_comment, mHomeCommentFragment = HomeCommentFragment.newInstance(videoId, headUrl, commentCount, position), false);
        mHomeCommentFragment.setOnCommentListener(new HomeCommentFragment.OnCommentListener() {
            @Override
            public void onDismiss() {
                hideReviewFragment();
            }

            @Override
            public void onSlide(float ratio) {
            }
        });
        tabHome.postDelayed(() -> {
            showReviewFragment();
        }, 200);
    }

    private void initReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addDataScheme("package");
        registerReceiver(receiver, intentFilter);
    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null || intent.getAction() == null || intent.getData() == null) {
                return;
            }
            switch (intent.getAction()) {
                case Intent.ACTION_PACKAGE_ADDED:
                case Intent.ACTION_PACKAGE_REPLACED:
                    String packageName = intent.getData().getSchemeSpecificPart();
                    MLog.logd(packageName + " 安装或替换成功");
                    reportMg(packageName);
                    break;
            }
        }
    };

    private synchronized void reportMg(String packageName) {
        try {
            if (!TextUtils.isEmpty(packageName) && ShuaApplication.adMap != null) {
                if (ShuaApplication.adMap.containsKey(packageName)) {
                    AdDataBean adDataBean = ShuaApplication.adMap.get(packageName);
                    MGReportManager.getInstance().startReport(ReportLocationType.endInstall, adDataBean);
                    ShuaApplication.adMap.remove(packageName);
                }
            }
        } catch (Exception e) {

        }
    }

    /**
     * 接受H5跳转事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onJumpEvent(JumpJson event) {
        if (event == null || TextUtils.isEmpty(event.getType())) {
            return;
        }
        switch (event.getType()) {
            case "home":
                openHome();
                break;
            case "hot_share":
                openHot();
                break;
            case "task":
                openGift();
                break;
            case "friend":
                startActivity(new Intent(this, H5Activity.class).putExtra("money", Constants.H5_URL + "helpEarn").putExtra("title", "邀请好友").putExtra("Refresh", true));
                break;
            case "xdraw":
                startActivityForResult(new Intent(this, H5Activity.class).putExtra("money", Constants.H5_URL + "withdraw").putExtra("title", "我的钱包"), WITHDRAW);
                break;
            case "turntable":
                startActivity(new Intent(this, H5Activity.class).putExtra("money", Constants.H5_URL + "activity_turntable").putExtra("title", "幸运大转盘"));
                break;
            case "jiangchi":
                startActivity(new Intent(this, H5Activity.class).putExtra("money", Constants.H5_URL + "activity_jiangchi").putExtra("title", "瓜分千万金豆"));
                break;
        }
    }

    @Override
    public boolean isRegisterEventBus() {
        return true;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN && homeFragment.isVisible() && MistakeConfigManager.getInstance().isDisDraw()) {
            float downY = ev.getRawY();
            int screenHeight = getResources().getDisplayMetrics().heightPixels;
            if (downY > screenHeight / 2 && downY < (screenHeight - DensityUtil.dip2px(mContext, 60))) {
                if (homeFragment != null) {
                    homeFragment.autoClickAd();
                }
            }
        }
        return super.dispatchTouchEvent(ev);
    }
}
